package com.westa.smallshop.data.source.remote;

import android.content.Context;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Response;
import com.westa.smallshop.data.HttpError;
import com.westa.smallshop.data.source.ImageSource;
import com.westa.smallshop.util.HttpUtils;
import com.westa.smallshop.util.volley.MultipartRequest;
import com.westa.smallshop.util.volley.VolleySingleton;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

/**
 * Created by Dune on 16/8/14.
 */
public class ImageRemoteSource implements ImageSource {

    public static final String TAG = "image";
    private static final String IMAGE_UPLOAD_URL = HttpUtils.getHost() + "imgUpload";

    private Context mContext;

    public ImageRemoteSource(Context context) {

        mContext = context;
    }

    @Override
    public void cancelLoadRequest() {

        VolleySingleton.cancelRequestForStartWithTag(TAG);

    }

    @Override
    public void upLoadImage(String image, final BaseDataSource.LoadCallBack<String> loadCallBack) {
        MultipartRequest<JSONObject> request = new MultipartRequest<>(IMAGE_UPLOAD_URL, JSONObject.class,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        loadCallBack.onLoadDataSuccessful(response.getString("url"));
                    }
                },
                new HttpUtils.ErrorListener(mContext) {

                    @Override
                    public void onErrorData(@Nullable HttpError httpError) {
                        loadCallBack.onLoadDataFailed();
                        Timber.e("图片"+httpError.getContent());
                    }
                });

        File file = new File(image);
        request.addParam("file", file);
        VolleySingleton.addRequest(request, TAG);
    }

    @Override
    public void upLoadImages(final List<String> images, final LoadCallBack<List<String>> listLoadCallBack) {
        final List<String> imageIds = new ArrayList<>();
        for (final String image : images) {
            upLoadImage(image, new LoadCallBack<String>() {
                @Override
                public void onLoadDataSuccessful(String data) {
                    imageIds.add(data);
                    if (imageIds.size() == images.size()) {
                        listLoadCallBack.onLoadDataSuccessful(imageIds);
                    }
                }

                @Override
                public void onLoadDataFailed() {
                    listLoadCallBack.onLoadDataFailed();
                    cancelLoadRequest();
                }
            });
        }
    }
}
